
//
//  AddCaseController.m
//  KMedicine
//
//  Created by song on 16/7/6.
//  Copyright © 2016年 caomu. All rights reserved.
//

#import "AddCaseController.h"
#import "CaseDefaultCell.h"
#import "CaseImageCell.h"
#import "CaseTextCell.h"
#import "ListController.h"
#import "AkuNetWorkTool.h"
#import "CaseModel.h"
#import "YYListModel.h"


@interface AddCaseController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) NSArray *caseArray;
@property (nonatomic, strong) UIImage *img;
@property (nonatomic, strong) CaseImageCell* theCell;
@property (nonatomic, strong) NSArray *caseNameArray;

@property (nonatomic, assign) NSInteger idx;
@property (nonatomic, strong) NSArray *modelArray;

@property (nonatomic, strong) YYListModel *arcModel;
@end

NSArray *temparr;

@implementation AddCaseController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 需要设置高度,
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.001)];
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(didRightItem:)];

}

#pragma mark
#pragma mark 设置 提交 按钮  存储数据
- (void)didRightItem:(UIBarButtonItem *)sender{
    
    // 提醒弹出窗口
    if (!self.arcModel.illName) {
        [self noticesWindow];
        return;
    }
    
    
    NSDate *date = [NSDate date];
    NSDateFormatter *f = [NSDateFormatter new];
    f.dateFormat = @"YYYY-MM-dd HH-mm-ss";
    self.arcModel.time = [f stringFromDate:date];

    self.arcModel.illImage = self.img;
    
    CaseTextCell *cell = (CaseTextCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    
    // 通过 cell kvc赋值
    UITextView *texFilr = [cell valueForKey:@"titleField"];
    
    self.arcModel.illDetail = texFilr.text.length ? texFilr.text : @"暂无描述";

    NSMutableArray *arr = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:kFilePath(@"user.data")]];
    [arr addObject:self.arcModel];
    
    [NSKeyedArchiver archiveRootObject:arr toFile:kFilePath(@"user.data")];

    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark
#pragma mark 设置标题
- (void)viewDidLayoutSubviews{
    
    self.navigationItem.title = self.navTitle;
}

- (void)noticesWindow{
    
        [SVProgressHUD showSuccessWithStatus:@"请选择疾病类型!"];//显示
        [SVProgressHUD setFadeInAnimationDuration:0];
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        [SVProgressHUD dismissWithDelay:1];
        
    
}

#pragma mark
#pragma mark 代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0 && indexPath.row == 1) {
        if (!self.arcModel.illName) {
            [self noticesWindow];
            return;
        }
    }

    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    ListController *caseList = [[ListController alloc] init];
    
    caseList.arrayBlock = ^(NSInteger idx){
        
        CaseModel *model = self.modelArray[indexPath.row];
        
        if (indexPath.row == 0) {

            
            model.subtitle =self.caseNameArray[idx];
            
            self.arcModel.illName = self.caseNameArray[idx];
            [self.tableView reloadData];
            
            
        } else {
            
            model.subtitle = temparr[idx];
            self.arcModel.illbase = temparr[idx];
            // 刷新详细病例列表数据,
            [self.tableView reloadData];
            // 刷新后 不需要获取网路数据  return
            return ;
            
        }
        
        // 获取网络数据
        NSString *listStr = [NSString stringWithFormat:@"%ld",idx + 1];
        
        NSDictionary * dic1 = @{@"page":@1,@"page_size":@15,@"ci1_id":listStr,@"keyword":@""};
        [AkuNetWorkTool POST_RequestWithURLString:@"http://iosapi.itcast.cn/searchCI3List.json.php" params:dic1 successBlock:^(id responseObject) {
            
            NSArray * array = responseObject[@"data"];
            NSMutableArray *mutable = [NSMutableArray array];
            [array enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                NSString * str = obj[@"ci3_name"];
                
                [mutable addObject:str];
            }];
            
            // MARK: 可变数组, 数据的数组
            temparr = mutable.copy;
            
        } errorBlock:^(NSError *error) {
            NSLog(@"error");
            
        }];
    };
    
    if (indexPath.section == 0) {
        
        if (indexPath.row == 0) {
            
            //MARK: 更换第一行数据之后,  重置第二行数据
            CaseModel *modelTemp = self.modelArray[1];
            modelTemp.subtitle = @"";
            
            // 如果是 第0组 第0行  传递数据
            caseList.listArr = self.caseNameArray;
        }else{
            
            // 第0组 第1行  传递数据
            caseList.listArr = temparr;
            
        }
        [self.navigationController pushViewController:caseList animated:YES];
    }
    
    //键盘消失
    [self.view endEditing:YES];
    
}

#pragma mark
#pragma mark 数据源代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.caseArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSDictionary *dict = self.caseArray[section];
    NSArray *temp = dict[@"Items"];
    
    return temp.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    // 取出 数据
    NSDictionary *dict = self.caseArray[indexPath.section];
    NSArray *temp = dict[@"Items"];
    NSDictionary *tempDict = temp[indexPath.row];
    
    // 通过 运行时判断 classType 类型, 并创建
    Class classType = NSClassFromString(tempDict[@"cellType"]);
    
    if ([classType isSubclassOfClass:[CaseImageCell class]]) {

        CaseImageCell* cell = [[CaseImageCell alloc] init];
        
        cell.pickerBlock = ^(CaseImageCell *caseCell){
            
            UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
            
//            pickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            
            __weak typeof(self) weakSelf = self;
            pickerController.delegate = weakSelf;
            
            weakSelf.theCell = caseCell;
            [weakSelf presentViewController:pickerController animated:YES completion:^{
                
            }];

        };
        
        cell.dict = tempDict;

        return cell;
        
    }else if([classType isSubclassOfClass:[CaseTextCell class]]){
        
        CaseTextCell* cell = [[classType alloc] init];
        
        cell.dict = tempDict;

        
        return cell;
    }else{
        
        CaseDefaultCell* cell = [[classType alloc] init];
        
        cell.dict = tempDict;
        cell.model = self.modelArray[indexPath.row];
        
        return cell;
    }
}

#pragma mark
#pragma mark 从相册获取图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *drawImg = info[UIImagePickerControllerOriginalImage];
    
    [UIImagePNGRepresentation(drawImg) writeToFile:kFilePath(@"b1.png") atomically:YES];
    
    self.img = [UIImage getMinImage:drawImg withWidth:80.0 withHeight:80.0];
    
    [UIImagePNGRepresentation(self.img) writeToFile:kFilePath(@"a1.png") atomically:YES];
    
    self.theCell.addView.image = self.img;

    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    // 取出 数据
    NSDictionary *dict = self.caseArray[indexPath.section];
    NSArray *temp = dict[@"Items"];
    NSDictionary *tempDict = temp[indexPath.row];
    
    NSString *str = tempDict[@"accessoryType"];
    
    if (str.boolValue) {
        return 44;
    }else{
        return 150;
    }
}

#pragma mark
#pragma mark 懒加载
- (NSArray *)caseArray{
    if (_caseArray == nil) {
        
        NSString *str = [[NSBundle mainBundle] pathForResource:self.plistName ofType:nil];
        _caseArray = [NSArray arrayWithContentsOfFile:str];
        
    }
    return _caseArray;
}

- (NSArray *)caseNameArray{
    
    if (_caseNameArray == nil) {

        _caseNameArray = @[@"肿瘤科",@"心血管科",@"血液科",@"神经科",@"骨科"];
        
    }
    return _caseNameArray;
}

- (NSArray *)modelArray{
    if (_modelArray == nil) {
        
        NSDictionary *dict = self.caseArray[0];
        NSArray *temp = dict[@"Items"];
        
        NSMutableArray *mutableTemp = [NSMutableArray array];
        [temp enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CaseModel *model = [CaseModel caseModel:obj];
            [mutableTemp addObject:model];
        }];
        
        _modelArray = mutableTemp.copy;
    }
    return _modelArray;
}



- (YYListModel *)arcModel{
    if (_arcModel == nil) {
        _arcModel = [YYListModel new];
    }
    return _arcModel;
}

#pragma mark
#pragma mark 初始化
- (instancetype)init{
    if (self = [super init]) {
        
    }
    return [self initWithStyle:UITableViewStyleGrouped];
}

@end
